package com.acme.bankapp.service.bank;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Date;

import com.acme.bankapp.domain.bank.Bank;
import com.acme.bankapp.domain.bank.Bank.DebugListener;
import com.acme.bankapp.domain.bank.Bank.EmailNotificationListener;
import com.acme.bankapp.domain.bank.Bank.PrintClientListener;
import com.acme.bankapp.domain.client.Client;
import com.acme.bankapp.domain.client.ClientRegistrationListener;
import com.acme.bankapp.domain.exception.ClientExistsException;

public class BankService {
	
	static public void addClient(Bank bank, Client client) throws ClientExistsException{
		bank.addClient(client);
	}
	
	static public boolean isAClietnOfBank(Bank bank,Client client){
		return bank.getClient(client) != null ? true : false;
	}
	
	static public Bank createNewBank(){
		return new Bank();
	}
	
	static public Bank createNewBankWithLisners(){
		return new Bank(clientRegistrationListenersCreator());
	}
	
	 private static ClientRegistrationListener[] clientRegistrationListenersCreator() {
         return new ClientRegistrationListener[]{new DebugListener(), new EmailNotificationListener(), new PrintClientListener()};
	 }
	
	
	static public void printBalance(Bank bank){
		for (Client client : bank.getClients()) {
			if(client == null)
				continue;
			System.out.println(client);
		}
		
	}
	
	static public void printMaximumAmountToWithdraw(Bank bank){
		for (Client client : bank.getClients()) {
			if(client == null)
				continue;
			System.out.println("maximumAmountToWithdraw = " + client.getAccount().maximumAmountToWithdraw());
		}
	}
	
	public static String getBalance(Bank bank){
		StringBuffer sb = new StringBuffer();
        for (Client client : bank.getClients()) {
                if (client != null) {
                        sb.append(client.toString()).append("\n");
                }
        }
        return sb.toString();
	}

	static public void saveBank(Bank bank, String path) throws FileNotFoundException,
			IOException {
		ObjectOutputStream oos = null;
		try {
			oos = new ObjectOutputStream(new FileOutputStream(path));
			oos.writeObject(bank);
		} finally {
			oos.close();
		}

	}

	static public Bank loadBank(String path) throws FileNotFoundException, IOException, ClassNotFoundException {

		ObjectInputStream ois = null;
		try {
			ois = new ObjectInputStream(new FileInputStream(path));
			Bank bank = (Bank) ois.readObject();

			return bank;
		} finally {

			ois.close();
		}

	}
}
